import React, { useState, useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { useTranslation } from 'react-i18next'
import {
  KeyIcon,
  PlusIcon,
  EyeIcon,
  EyeSlashIcon,
  TrashIcon,
  PencilIcon,
  ClockIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon,
  DocumentDuplicateIcon,
  CalendarIcon,
  GlobeAltIcon
} from '@heroicons/react/24/outline'
import { AppDispatch } from '@/store'
import { Card, Button, Input, Badge, Modal, ConfirmModal, LoadingSkeleton } from '@/components/ui'
import { ErrorBoundary } from '@/components/common'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'

// Mock data - 在实际应用中，这些数据应该从API获取
const mockApiKeys = [
  {
    id: '1',
    name: 'Production API Key',
    keyPrefix: 'bh_a1b2c3d4',
    permissions: ['plugin:read', 'plugin:write', 'analytics:read'],
    rateLimitPerHour: 1000,
    lastUsedAt: '2024-01-15T10:30:00Z',
    lastUsedIp: '192.168.1.100',
    expiresAt: '2025-01-01T00:00:00Z',
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: '2024-01-01T00:00:00Z'
  },
  {
    id: '2',
    name: 'Development Key',
    keyPrefix: 'bh_e5f6g7h8',
    permissions: ['plugin:read'],
    rateLimitPerHour: 500,
    lastUsedAt: '2024-01-14T15:45:00Z',
    lastUsedIp: '192.168.1.101',
    expiresAt: undefined,
    createdAt: '2024-01-05T00:00:00Z',
    updatedAt: '2024-01-05T00:00:00Z'
  },
  {
    id: '3',
    name: 'Testing Key',
    keyPrefix: 'bh_i9j0k1l2',
    permissions: ['plugin:read', 'analytics:read'],
    rateLimitPerHour: 100,
    lastUsedAt: undefined,
    lastUsedIp: undefined,
    expiresAt: '2024-06-01T00:00:00Z',
    createdAt: '2024-01-10T00:00:00Z',
    updatedAt: '2024-01-10T00:00:00Z'
  }
]

const availablePermissions = [
  { value: 'plugin:read', label: 'Read Plugins', description: 'View plugin information and download' },
  { value: 'plugin:write', label: 'Write Plugins', description: 'Upload and modify plugins' },
  { value: 'plugin:delete', label: 'Delete Plugins', description: 'Delete plugins and versions' },
  { value: 'analytics:read', label: 'Read Analytics', description: 'View download and usage statistics' },
  { value: 'user:read', label: 'Read Profile', description: 'Access user profile information' }
]

const createApiKeySchema = z.object({
  name: z.string()
    .min(3, 'Name must be at least 3 characters')
    .max(100, 'Name must be less than 100 characters'),
  permissions: z.array(z.string()).min(1, 'At least one permission is required'),
  rateLimitPerHour: z.number()
    .min(1, 'Rate limit must be at least 1')
    .max(10000, 'Rate limit cannot exceed 10,000'),
  expiresAt: z.string().optional()
})

type CreateApiKeyFormData = z.infer<typeof createApiKeySchema>

interface ApiKey {
  id: string
  name: string
  keyPrefix: string
  permissions: string[]
  rateLimitPerHour: number
  lastUsedAt?: string
  lastUsedIp?: string
  expiresAt?: string
  createdAt: string
  updatedAt: string
}

interface NewApiKeyResponse {
  apiKey: ApiKey
  secretKey: string
}

export const ApiKeysPage: React.FC = () => {
  const { t } = useTranslation()
  const dispatch = useDispatch<AppDispatch>()
  const [apiKeys, setApiKeys] = useState<ApiKey[]>(mockApiKeys)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Modal states
  const [createModalOpen, setCreateModalOpen] = useState(false)
  const [newKeyModalOpen, setNewKeyModalOpen] = useState(false)
  const [deleteModalOpen, setDeleteModalOpen] = useState(false)
  const [keyToDelete, setKeyToDelete] = useState<string | null>(null)
  const [newApiKeyData, setNewApiKeyData] = useState<NewApiKeyResponse | null>(null)

  // Visibility states for API keys
  const [visibleKeys, setVisibleKeys] = useState<Set<string>>(new Set())

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
    watch,
    setValue
  } = useForm<CreateApiKeyFormData>({
    resolver: zodResolver(createApiKeySchema),
    defaultValues: {
      rateLimitPerHour: 1000,
      permissions: ['plugin:read']
    }
  })

  const selectedPermissions = watch('permissions') || []

  useEffect(() => {
    // 在实际应用中，这里应该调用API获取数据
    // dispatch(fetchApiKeys())
  }, [dispatch])

  const handleCreateApiKey = async (data: CreateApiKeyFormData) => {
    setIsLoading(true)
    setError(null)

    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))

      const newKey: NewApiKeyResponse = {
        apiKey: {
          id: Date.now().toString(),
          name: data.name,
          keyPrefix: `bh_${Math.random().toString(36).substring(2, 10)}`,
          permissions: data.permissions,
          rateLimitPerHour: data.rateLimitPerHour,
          expiresAt: data.expiresAt || undefined,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        },
        secretKey: `bh_${Math.random().toString(36).substring(2, 10)}_${Math.random().toString(36).substring(2, 26)}`
      }

      setApiKeys(prev => [newKey.apiKey, ...prev])
      setNewApiKeyData(newKey)
      setCreateModalOpen(false)
      setNewKeyModalOpen(true)
      reset()
    } catch (error) {
      setError('Failed to create API key. Please try again.')
    } finally {
      setIsLoading(false)
    }
  }

  const handleDeleteApiKey = async () => {
    if (!keyToDelete) return

    setIsLoading(true)
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))

      setApiKeys(prev => prev.filter(key => key.id !== keyToDelete))
      setDeleteModalOpen(false)
      setKeyToDelete(null)
    } catch (error) {
      setError('Failed to delete API key. Please try again.')
    } finally {
      setIsLoading(false)
    }
  }

  const toggleKeyVisibility = (keyId: string) => {
    setVisibleKeys(prev => {
      const newSet = new Set(prev)
      if (newSet.has(keyId)) {
        newSet.delete(keyId)
      } else {
        newSet.add(keyId)
      }
      return newSet
    })
  }

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text)
      // 这里可以添加一个toast通知
    } catch (error) {
      console.error('Failed to copy to clipboard:', error)
    }
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  const isExpired = (expiresAt?: string) => {
    if (!expiresAt) return false
    return new Date(expiresAt) < new Date()
  }

  const getPermissionBadgeVariant = (permission: string) => {
    if (permission.includes('write') || permission.includes('delete')) return 'danger'
    if (permission.includes('analytics')) return 'primary'
    return 'gray'
  }

  return (
    <ErrorBoundary>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">{t('apiKeys.title')}</h1>
            <p className="text-gray-600 mt-1">
              {t('apiKeys.subtitle')}
            </p>
          </div>
          <Button
            onClick={() => setCreateModalOpen(true)}
            icon={<PlusIcon />}
            disabled={isLoading}
          >
            {t('apiKeys.createNew')}
          </Button>
        </div>

        {/* Error Alert */}
        {error && (
          <div className="flex items-center p-4 bg-red-50 border border-red-200 rounded-md">
            <ExclamationTriangleIcon className="h-5 w-5 text-red-400 mr-3" />
            <div className="text-sm text-red-700">{error}</div>
          </div>
        )}

        {/* API Keys List */}
        <div className="space-y-4">
          {isLoading && apiKeys.length === 0 ? (
            <div className="space-y-4">
              <LoadingSkeleton className="h-32" />
              <LoadingSkeleton className="h-32" />
              <LoadingSkeleton className="h-32" />
            </div>
          ) : apiKeys.length === 0 ? (
            <Card className="p-12 text-center">
              <div className="mx-auto w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                <KeyIcon className="h-8 w-8 text-gray-400" />
              </div>
              <h3 className="text-lg font-medium text-gray-900 mb-2">{t('apiKeys.noKeys')}</h3>
              <p className="text-gray-600 mb-6">
                {t('apiKeys.noKeysDescription')}
              </p>
              <Button
                onClick={() => setCreateModalOpen(true)}
                icon={<PlusIcon />}
              >
                {t('apiKeys.createFirst')}
              </Button>
            </Card>
          ) : (
            apiKeys.map((apiKey) => (
              <Card key={apiKey.id} className="p-6">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center space-x-3 mb-3">
                      <h3 className="text-lg font-medium text-gray-900">{apiKey.name}</h3>
                      {isExpired(apiKey.expiresAt) && (
                        <Badge variant="danger">{t('apiKeys.expired')}</Badge>
                      )}
                    </div>

                    {/* API Key Display */}
                    <div className="mb-4">
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        {t('apiKeys.apiKey')}
                      </label>
                      <div className="flex items-center space-x-2">
                        <div className="flex-1 font-mono text-sm bg-gray-50 border rounded-md px-3 py-2">
                          {visibleKeys.has(apiKey.id)
                            ? `${apiKey.keyPrefix}_${'*'.repeat(24)}`
                            : `${apiKey.keyPrefix}_${'*'.repeat(24)}`
                          }
                        </div>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => toggleKeyVisibility(apiKey.id)}
                          icon={visibleKeys.has(apiKey.id) ? <EyeSlashIcon /> : <EyeIcon />}
                        >
                          {visibleKeys.has(apiKey.id) ? t('common.hide') : t('common.show')}
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => copyToClipboard(`${apiKey.keyPrefix}_example_key`)}
                          icon={<DocumentDuplicateIcon />}
                        >
                          {t('common.copy')}
                        </Button>
                      </div>
                    </div>

                    {/* Permissions */}
                    <div className="mb-4">
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        {t('apiKeys.permissions')}
                      </label>
                      <div className="flex flex-wrap gap-2">
                        {apiKey.permissions.map((permission) => (
                          <Badge
                            key={permission}
                            variant={getPermissionBadgeVariant(permission)}
                          >
                            {permission}
                          </Badge>
                        ))}
                      </div>
                    </div>

                    {/* Metadata */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm text-gray-600">
                      <div className="flex items-center space-x-2">
                        <GlobeAltIcon className="h-4 w-4" />
                        <span>{t('apiKeys.rateLimit')}: {apiKey.rateLimitPerHour}/{t('apiKeys.hour')}</span>
                      </div>

                      {apiKey.lastUsedAt ? (
                        <div className="flex items-center space-x-2">
                          <ClockIcon className="h-4 w-4" />
                          <span>{t('apiKeys.lastUsed')}: {formatDate(apiKey.lastUsedAt)}</span>
                        </div>
                      ) : (
                        <div className="flex items-center space-x-2">
                          <ClockIcon className="h-4 w-4" />
                          <span>{t('apiKeys.neverUsed')}</span>
                        </div>
                      )}

                      {apiKey.expiresAt ? (
                        <div className="flex items-center space-x-2">
                          <CalendarIcon className="h-4 w-4" />
                          <span className={isExpired(apiKey.expiresAt) ? 'text-red-600' : ''}>
                            {t('apiKeys.expires')}: {formatDate(apiKey.expiresAt)}
                          </span>
                        </div>
                      ) : (
                        <div className="flex items-center space-x-2">
                          <CalendarIcon className="h-4 w-4" />
                          <span>{t('apiKeys.neverExpires')}</span>
                        </div>
                      )}
                    </div>

                    {apiKey.lastUsedIp && (
                      <div className="mt-2 text-sm text-gray-600">
                        {t('apiKeys.lastUsedFromIP')}: {apiKey.lastUsedIp}
                      </div>
                    )}
                  </div>

                  {/* Actions */}
                  <div className="flex items-center space-x-2 ml-4">
                    <Button
                      size="sm"
                      variant="outline"
                      icon={<PencilIcon />}
                      disabled={isExpired(apiKey.expiresAt)}
                    >
                      {t('common.edit')}
                    </Button>
                    <Button
                      size="sm"
                      variant="danger"
                      icon={<TrashIcon />}
                      onClick={() => {
                        setKeyToDelete(apiKey.id)
                        setDeleteModalOpen(true)
                      }}
                    >
                      {t('common.delete')}
                    </Button>
                  </div>
                </div>
              </Card>
            ))
          )}
        </div>

        {/* Create API Key Modal */}
        <Modal
          isOpen={createModalOpen}
          onClose={() => setCreateModalOpen(false)}
          title={t('apiKeys.createNew')}
          size="lg"
        >
          <form onSubmit={handleSubmit(handleCreateApiKey)} className="space-y-6">
            <div>
              <Input
                label={t('apiKeys.form.name')}
                placeholder={t('apiKeys.form.namePlaceholder')}
                error={errors.name?.message}
                {...register('name')}
                fullWidth
              />
              <p className="mt-1 text-sm text-gray-500">
                {t('apiKeys.form.nameHelper')}
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-3">
                {t('apiKeys.permissions')}
              </label>
              <div className="space-y-3">
                {availablePermissions.map((permission) => (
                  <div key={permission.value} className="flex items-start space-x-3">
                    <input
                      type="checkbox"
                      id={permission.value}
                      value={permission.value}
                      checked={selectedPermissions.includes(permission.value)}
                      onChange={(e) => {
                        const currentPermissions = selectedPermissions || []
                        if (e.target.checked) {
                          setValue('permissions', [...currentPermissions, permission.value])
                        } else {
                          setValue('permissions', currentPermissions.filter(p => p !== permission.value))
                        }
                      }}
                      className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded mt-0.5"
                    />
                    <div className="flex-1">
                      <label htmlFor={permission.value} className="text-sm font-medium text-gray-900 cursor-pointer">
                        {permission.label}
                      </label>
                      <p className="text-sm text-gray-500">{permission.description}</p>
                    </div>
                  </div>
                ))}
              </div>
              {errors.permissions && (
                <p className="mt-1 text-sm text-red-600">{errors.permissions.message}</p>
              )}
            </div>

            <div>
              <Input
                label={t('apiKeys.form.rateLimit')}
                type="number"
                placeholder="1000"
                error={errors.rateLimitPerHour?.message}
                {...register('rateLimitPerHour', { valueAsNumber: true })}
                fullWidth
              />
              <p className="mt-1 text-sm text-gray-500">
                {t('apiKeys.form.rateLimitHelper')}
              </p>
            </div>

            <div>
              <Input
                label={t('apiKeys.form.expirationDate')}
                type="datetime-local"
                error={errors.expiresAt?.message}
                {...register('expiresAt')}
                fullWidth
              />
              <p className="mt-1 text-sm text-gray-500">
                {t('apiKeys.form.expirationHelper')}
              </p>
            </div>

            <div className="flex items-center justify-end space-x-3 pt-4 border-t">
              <Button
                type="button"
                variant="outline"
                onClick={() => setCreateModalOpen(false)}
              >
                {t('common.cancel')}
              </Button>
              <Button
                type="submit"
                loading={isLoading}
                disabled={isLoading}
              >
                {t('apiKeys.createNew')}
              </Button>
            </div>
          </form>
        </Modal>

        {/* New API Key Display Modal */}
        <Modal
          isOpen={newKeyModalOpen}
          onClose={() => setNewKeyModalOpen(false)}
          title={t('apiKeys.createSuccess')}
          size="lg"
        >
          <div className="space-y-6">
            <div className="flex items-center p-4 bg-green-50 border border-green-200 rounded-md">
              <CheckCircleIcon className="h-5 w-5 text-green-400 mr-3" />
              <div className="text-sm text-green-700">
                {t('apiKeys.createSuccessMessage')}
              </div>
            </div>

            {newApiKeyData && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t('apiKeys.yourNewKey')}
                </label>
                <div className="flex items-center space-x-2">
                  <div className="flex-1 font-mono text-sm bg-gray-50 border rounded-md px-3 py-2 break-all">
                    {newApiKeyData.secretKey}
                  </div>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => copyToClipboard(newApiKeyData.secretKey)}
                    icon={<DocumentDuplicateIcon />}
                  >
                    Copy
                  </Button>
                </div>
              </div>
            )}

            <div className="bg-yellow-50 border border-yellow-200 rounded-md p-4">
              <div className="flex items-start">
                <ExclamationTriangleIcon className="h-5 w-5 text-yellow-400 mt-0.5 mr-3 flex-shrink-0" />
                <div className="text-sm text-yellow-700">
                  <p className="font-medium mb-1">Important Security Notice:</p>
                  <ul className="list-disc list-inside space-y-1">
                    <li>Store this API key securely</li>
                    <li>Never share it in public repositories</li>
                    <li>Use environment variables in your applications</li>
                    <li>Regenerate the key if you suspect it's been compromised</li>
                  </ul>
                </div>
              </div>
            </div>

            <div className="flex items-center justify-end space-x-3 pt-4 border-t">
              <Button
                onClick={() => setNewKeyModalOpen(false)}
                variant="primary"
              >
                I've Saved My API Key
              </Button>
            </div>
          </div>
        </Modal>

        {/* Delete Confirmation Modal */}
        <ConfirmModal
          isOpen={deleteModalOpen}
          onClose={() => setDeleteModalOpen(false)}
          onConfirm={handleDeleteApiKey}
          title="Delete API Key"
          message="Are you sure you want to delete this API key? This action cannot be undone and will immediately revoke access for any applications using this key."
          confirmText="Delete API Key"
          variant="danger"
        />
      </div>
    </ErrorBoundary>
  )
}
